package com.dap.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5 hash算法
 */
public class Md5Util {
    private static Logger logger = LoggerFactory.getLogger(Md5Util.class);

    public static String md5(String str) {
        return md5(str, true);
    }

    public static String md5(String str, boolean zero) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            logger.warn("", ex);
            return null;
        }
        byte[] resultByte = messageDigest.digest(str.getBytes());
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < resultByte.length; ++i) {
            int v = 0xFF & resultByte[i];
            if (v < 16 && zero)
                result.append("0");
            result.append(Integer.toHexString(v));
        }
        return result.toString();
    }


    public static void main(String[] args) {
        System.out.println(md5("123456"));
    }


}
